package com.xiaohai.wx.weather.message;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

@Service("SessionHandler")
public class SessionHandler {
	
	private static Map<String, ChatSession> sessionMap = new HashMap<String, ChatSession>();
	
	public static String TOPIC_QUERY_LOCATION = "queryLocation";
	
	public void setTopic(String openId, String topic){
		if(sessionMap.containsKey(openId)){
			ChatSession session = sessionMap.get(openId);
			session.setTopic(topic);
			session.setLastMessageTime(new Date());
		}else{
			ChatSession session = new ChatSession();
			session.setLastMessageTime(new Date());
			session.setTopic(topic);
			sessionMap.put(openId, session);
		}
	}
	
	public String getTopic(String openId){
		
		ChatSession session = sessionMap.get(openId);
		if(session == null){
			return null;
		}else{
			return session.getTopic();
		}
	}
	
	public void removeSession(String openId){
		sessionMap.remove(openId);
	}
	
	public static void clearSession(){
		for(Map.Entry<String, ChatSession> entry : sessionMap.entrySet()){
			ChatSession session = entry.getValue();
			String key = entry.getKey();
			Date now = new Date();
            // in milliseconds
            long diff = now.getTime() - session.getLastMessageTime().getTime();
            long diffMinutes = diff / (60 * 1000);
            if (diffMinutes > 30)
            {
                sessionMap.remove(key);
            }
		}
	}

}
